package hehe.aop.annotation;

import hehe.aop.Aop;
import hehe.aop.AopManager;
import hehe.aop.base.Behavior;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 事件注解处理器基类
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class BaseAspectProcessor
{
    /**
     * 当前注解
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected Annotation annotation;

    /**
     * 当前行为通知点
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected String advice;


    public void configure(Annotation annotation, String advice)
    {
        this.annotation = annotation;
        this.advice = advice;
    }

    /**
     * 注册行为
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    public void addAspect(String expression)
    {
        Class<? extends Behavior>[] behavior = this.getAnnotationAttr("behavior");
        Aop.getAopManager().addAspect(behavior,this.advice,expression);
    }

    /**
     * 获取注解属性值
     *<B>说明：</B>
     *<pre>
     *  通过反射调用注解方法,获取数据
     *</pre>
     * @param attrName 注解方法名
     */
    protected <T> T getAnnotationAttr(String attrName)
    {
        try {
            Method method = this.annotation.getClass().getDeclaredMethod(attrName, (Class<?>[]) null);
            return (T)method.invoke(this.annotation,(Object[]) null);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 获取注解属性值
     *<B>说明：</B>
     *<pre>
     *  通过反射调用注解方法,获取数据
     *</pre>
     * @param attrName 注解方法名
     */
    protected <T> T getAnnotationAttr(String attrName,Annotation annotation)
    {
        try {
            Method method = annotation.getClass().getDeclaredMethod(attrName, (Class<?>[]) null);
            return (T)method.invoke(annotation,(Object[]) null);
        } catch (Exception ex) {
            return null;
        }
    }

}
